﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Dycox.Reporting
{
    internal class BoundsConverter : TypeConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            return sourceType == typeof(string) || sourceType == typeof(RectangleF) || sourceType == typeof(Rectangle) || base.CanConvertFrom(context, sourceType);
        }

        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            return destinationType == typeof(RectangleF) || base.CanConvertTo(context, destinationType);
        }

        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            if (value is string)
            {
                string text = (string)value;
                string[] array = Regex.Split(text, "\\s+");

                if (array.Length != 4)
                    throw new FormatException("Invalid bounds format.");

                return new Bounds(
                    float.Parse(array[0]),
                    float.Parse(array[1]),
                    float.Parse(array[2]),
                    float.Parse(array[3]));
            }
            else if (value is Rectangle)
            {
                return new Bounds((Rectangle)value);
            }
            else if (value is RectangleF)
            {
                return new Bounds((RectangleF)value);
            }

            return base.ConvertFrom(context, culture, value);
        }

        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType == typeof(string))
            {
                Bounds rect = (Bounds)value;
                return string.Format("{0} {1} {2} {3}", rect.Left, rect.Top, rect.Width, rect.Height);
            }
            else if (destinationType == typeof(RectangleF))
                return ((Bounds)value).ToRectangle();

            return base.ConvertTo(context, culture, value, destinationType);
        }
    }
}
